/*
 * @Date: 2022-05-20 16:55:22
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-05-20 19:36:48
 * @FilePath: \my-react-components\src\component\Tabs\index.tsx
 * @Description: something
 */
import classNames from "classnames";
import React, { createContext, memo, useState, useEffect } from "react";
import { TabItemProps } from "./TabItem";
type SelectCB = (selectIndex: string) => void;
export interface ITabs {
  children?: React.ReactNode;
  defaultIndex?: string;
  className?: string;
  onSelect?: SelectCB;
  border?: boolean;
}
interface ITabContext {
  index: string;
  onSelect?: SelectCB;
  getchildren?: (children: React.ReactNode) => void;
  border?: boolean;
}
export const tabContext = createContext<ITabContext>({ index: "0" });
const Tabs: React.FC<ITabs> = memo(
  ({ children, defaultIndex, className, onSelect, border }) => {
    const [currentActive, setCurrrentActive] = useState(defaultIndex);
    const [curChildren, setCurChildren] = useState<React.ReactNode>(null);
    const renderChildren = () => {
      return React.Children.map(children, (child, index) => {
        const childrenEl =
          child as React.FunctionComponentElement<TabItemProps>;
        const { displayName } = childrenEl.type;
        if (displayName === "TabItem") {
          return React.cloneElement(childrenEl, {
            index: index.toString(),
          });
        } else {
          console.error("在Tabs组件中子组件只能使用'TabItem'");
        }
      });
    };
    useEffect(() => {
      setCurChildren(children![0].props.children);
    }, []);
    const classes = classNames("sailor-tabs", className);
    const handleClick = (index: string) => {
      setCurrrentActive(index);
      if (onSelect) {
        onSelect(index);
      }
    };
    const getchildren = (children: React.ReactNode) => {
      setCurChildren(children);
    };
    const context: ITabContext = {
      index: currentActive ? currentActive : "0",
      onSelect: handleClick,
      getchildren,
      border,
    };
    return (
      <>
        <ul className={classes}>
          <tabContext.Provider value={context}>
            {renderChildren()}
          </tabContext.Provider>
        </ul>
        <div>{curChildren}</div>
      </>
    );
  },
);
Tabs.defaultProps = {
  defaultIndex: "0",
};
export default Tabs;
